<?php

namespace App\Http\Controllers;

use App\Constants\AdminUserConstant;
use App\Constants\ResponseCodeConstant;
use App\Exceptions\BusinessException;
use App\Http\Requests\AdminLoginRequest;
use App\Http\Requests\AdminRegisterRequest;
use App\Http\Requests\ResetPasswordRequest;
use App\Http\Requests\UpdatePasswordRequest;
use App\Http\Requests\UpdateStatusRequest;
use App\Services\AdminRoleService;
use App\Services\AdminUserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

/**
 * 后台用户管理
 * Class AdminUserController
 * @package App\Http\Controllers
 */
class AdminUserController extends BaseController
{

    /**
     * 用户注册
     * @param AdminRegisterRequest $request
     * @return mixed
     */
    public function register(AdminRegisterRequest $request)
    {
        $params = $request->only(['username','password','avatar','email','nick_name','note']);
        $data = [
          'username' => $params['username'],
          'password' => Hash::make($params['password']),
          'avatar' => $params['avatar'] ?? '',
          'email' => $params['email'] ?? '',
          'nick_name' => $params['nickname'] ?? '',
          'note' => $params['note'] ?? '',
          'status' => AdminUserConstant::STATUS_ON
        ];
        AdminUserService::getInstance()->register($data);
        $result = [
          'username' => $params['username']
        ];
        return $this->success($result,'注册成功');
    }

    /**
     * 用户登录
     * @param AdminLoginRequest $request
     * @return JsonResponse|mixed|object
     * @throws BusinessException
     */
    public function login(AdminLoginRequest $request)
    {
        $credentials = $request->only(['username','password']);
        $admin_user = AdminUserService::getInstance()->getByUsername($credentials['username']);
        $data = [
            'username' => $admin_user->username,
            'avatar' => $admin_user->avatar,
            'nick_name' => $admin_user->nick_name,
        ];
        if ($token = Auth::guard('admin')->attempt($credentials)) {
            $data['token'] = $token;
        } else {
            return $this->fail(ResponseCodeConstant::ACCOUNT_FAILED);
        }
        return $this->success($data,'登录成功');
    }

    /**
     * 刷新token
     * @return mixed
     */
    public function refresh()
    {
        $refresh_token = Auth::guard('api')->refresh();
        $data = [
          'refresh_token' => $refresh_token
        ];
        return $this->success($data,'刷新成功');
    }

    /**
     * 获取当前登录用户信息
     * @return mixed
     * @throws BusinessException
     */
    public function info()
    {
        $userId = Auth::guard('api')->id();
        $admin_user = AdminUserService::getInstance()->getUserRolesById($userId);
        // 获取用户角色列表
        $roleInfos = $admin_user->roles;
        $menus = [];
        if ($roleInfos->count() > 0) {
            $roleIds = array_column($roleInfos->toArray(),'id');
            $menus = AdminRoleService::getInstance()->getMenuByIds($roleIds);
        }
        $data = [
            'username' => $admin_user->username,
            'avatar' => $admin_user->avatar,
            'nick_name' => $admin_user->nick_name,
            'roles' =>$roleInfos,
            'menus' => $menus
        ];
        return $this->success($data,'成功');
    }

    /**
     * 登出
     * @return mixed
     */
    public function logout()
    {
        Auth::guard('api')->logout();
        return $this->success();
    }

    /**
     * 根据用户名或姓名分页获取用户列表
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        $keyword = $request->get('keyword');
        $pageSize = $request->get('pageSize',10);
        $pageNum = $request->get('pageNum',1);
        $pager = AdminUserService::getInstance()->getList($keyword,$pageSize,$pageNum);
        $data = $this->successPagniate($pager);
        return $this->success($data);
    }

    /**
     * 获取指定用户信息
     * @param Request $request
     * @return mixed
     * @throws BusinessException
     */
    public function getById(Request $request)
    {
        $userId = $request->route('id');
        $admin_user = AdminUserService::getInstance()->getById($userId);
        $data = [
            'username' => $admin_user->username,
            'avatar' => $admin_user->avatar,
            'nick_name' => $admin_user->nick_name,
        ];
        return $this->success($data,'成功');
    }

    /**
     * 修改指定用户信息
     * @param Request $request
     * @return mixed
     * @throws BusinessException
     */
    public function updateById(Request $request)
    {
        $userId = $request->route('id');
        $params = $request->only(['username','avatar','nick_name','note','email']);
        $data = [];
        if (isset($params['username'])) {
            $data['username'] = $params['username'];
        }
        if (isset($params['avatar'])) {
            $data['avatar'] = $params['avatar'];
        }
        if (isset($params['nick_name'])) {
            $data['nick_name'] = $params['nick_name'];
        }
        if (isset($params['note'])) {
            $data['note'] = $params['note'];
        }
        if (isset($params['email'])) {
            $data['email'] = $params['email'];
        }
        if ($data) {
            AdminUserService::getInstance()->updateById($data,$userId);
        }
        return $this->success();
    }

    /**
     *修改指定用户密码
     * @param UpdatePasswordRequest $request
     * @return mixed
     * @throws BusinessException
     */
    public function updatePassword(UpdatePasswordRequest $request)
    {
        $own_userId = Auth::user()->id;
        $password = $request->post('password');
        $userId = $request->post('user_id');
        if ($userId === $own_userId) {
            return $this->fail(ResponseCodeConstant::PARAMS_ERROR,'不能修改登录用户密码');
        }
        $data = [
          'password' => Hash::make($password)
        ];
        AdminUserService::getInstance()->updateById($data,$userId);
        return $this->success();
    }

    /**
     * 重置密码
     * @param ResetPasswordRequest $request
     * @return JsonResponse|mixed|object
     * @throws BusinessException
     */
    public function reset(ResetPasswordRequest $request)
    {
        $username = Auth::user()->username;
        $userId = Auth::user()->id;
        $old_password = $request->post('old_password');
        $password = $request->post('password');
        $credentials = [
          'username' => $username,
          'password' => $old_password
        ];
        if (Auth::guard('api')->attempt($credentials)) {
            $data = [
              'password' => Hash::make($password)
            ];
            AdminUserService::getInstance()->updateById($data,$userId);
            return $this->success();
        } else {
            return $this->fail(ResponseCodeConstant::ACCOUNT_FAILED,'原密码不正确');
        }
    }

    /**
     * 删除指定用户信息
     * @param Request $request
     * @return mixed
     * @throws BusinessException
     */
    public function delete(Request $request)
    {
        $userId = $request->post('id');
        AdminUserService::getInstance()->deleteById($userId);
        return $this->success();
    }

    /**
     * 修改帐号状态
     * @param UpdateStatusRequest $request
     * @return mixed
     * @throws BusinessException
     */
    public function updateStatus(UpdateStatusRequest $request)
    {
        $own_userId = Auth::user()->id;
        $userId = $request->route('id');
        if ($userId === $own_userId) {
            return $this->fail(ResponseCodeConstant::PARAMS_ERROR,'不能修改登录用户状态');
        }
        $data = [
          'status' => $request->post('status')
        ];
        AdminUserService::getInstance()->updateById($data,$userId);
        return $this->success();
    }

    /**
     * 给用户分配角色
     * @param Request $request
     * @return mixed
     * @throws BusinessException
     */
    public function updateRole(Request $request)
    {
        $adminId = $request->post('adminId');
        $roleIds = $request->post('roleIds');
        $originRoles = AdminUserService::getInstance()->getUserRolesById($adminId);
        $originRoleIds = array_column($originRoles,'id');
        $userInfo = AdminUserService::getInstance()->getUserRolesById($adminId);
        $userInfo->roles()->detach($originRoleIds);
        $userInfo->roles()->attach($roleIds);
        return $this->success();
    }

    /**
     * 获取指定用户的角色
     * @param Request $request
     * @return JsonResponse|mixed|object
     * @throws BusinessException
     */
    public function getRoleList(Request $request)
    {
        $adminId = $request->route('adminId');
        $roleInfo = AdminUserService::getInstance()->getUserRolesById($adminId);
        if ($roleInfo) {
            return $this->success($roleInfo);
        }
        return $this->fail(ResponseCodeConstant::SEARCH_FAILED,'获取用户角色列表失败');
    }
}
